import os
import sys
from flask import jsonify
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# from watchlist.chat import chatgpt_blue
from flask_jwt_extended import JWTManager
from dotenv import load_dotenv

load_dotenv()  # 从 .env 文件中加载环境变量

WIN = sys.platform.startswith('win')
if WIN:  # 如果是 Windows 系统，使用三个斜线
    prefix = 'sqlite:///'
else:  # 否则使用四个斜线
    prefix = 'sqlite:////'
app = Flask(__name__)

# 把蓝图注册到app上, 加前缀
# app.register_blueprint(chatgpt_blue, url_prefix='')

app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', '')
app.config['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY', '')
app.config['SQLALCHEMY_DATABASE_URI'] = prefix + os.path.join(os.path.dirname(app.root_path), os.getenv('DATABASE_FILE', 'watchlist/database.db'))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 关闭对模型修改的监控


# 配置 Flask-JWT-Extended
app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY')
jwt = JWTManager(app)

# print(app.config)

# 在扩展类实例化前加载配置
db = SQLAlchemy(app)

# 强制返回 JSON 格式的错误信息
@app.errorhandler(Exception)
def handle_error(e):
    app.logger.error(str(e))
    # 不返回真实报错信息
    # response = jsonify(error=str(e))
    response = jsonify(error='请求失败')
    response.status_code = 500
    return response

from watchlist import views, errors, commands